package com.link.linkupjavaweb.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.link.linkupjavaweb.dto.RankDTO;
import com.link.linkupjavaweb.entity.Rank;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 排行榜Mapper接口
 */
@Mapper
public interface RankMapper extends BaseMapper<Rank> {
    
    /**
     * 查询排行榜列表（使用视图v_rank_list）
     * @param limit 限制数量
     * @return 排行榜列表
     */
    @Select("SELECT " +
            "    u.id as userId, " +
            "    u.account, " +
            "    u.nickname, " +
            "    u.avatar, " +
            "    u.total_score as totalScore, " +
            "    u.win_count as winCount, " +
            "    u.lose_count as loseCount, " +
            "    u.game_count as gameCount, " +
            "    u.max_combo as maxCombo, " +
            "    CASE " +
            "        WHEN u.game_count > 0 THEN ROUND(u.win_count * 100.0 / u.game_count, 2) " +
            "        ELSE 0.00 " +
            "    END as winRate " +
            "FROM tb_user u " +
            "WHERE u.status = 0 " +
            "ORDER BY u.total_score DESC, u.win_count DESC " +
            "LIMIT #{limit}")
    List<RankDTO> selectRankList(@Param("limit") Integer limit);
    
    /**
     * 查询用户的排名
     * @param userId 用户ID
     * @return 排名位置（从1开始）
     */
    @Select("SELECT COUNT(*) + 1 FROM tb_user " +
            "WHERE status = 0 AND total_score > " +
            "(SELECT total_score FROM tb_user WHERE id = #{userId})")
    Integer selectUserRank(@Param("userId") Long userId);
}

